#! /usr/bin/env node
const program=require('commander')
const inquirer=require('inquirer')

const fs=require('fs')
const path=require('path')

//生成文件
let option=[{
    type:"input",
    message:"请输入文件名",
    name:"fileName"
},{
    type:"list",
    message:"请选择文件类型",
    name:"fileType",
    choices:['.html','.css','.scss','.js','.ts','.json']
},{
    type:'editor',
    message:'请输入文件内容(回车输入)',
    name:"content",
},{
    type:'confirm',
    message:"确定生成文件吗？",
    name:"isSure"
}]

program.command('create_file')
    .action(()=>{
        inquirer.prompt(option).then(res=>{
            console.log(res)
            const {fileName,fileType,content,isSure}=res
            if(isSure){
                fs.writeFile(fileName+fileType,content,(err)=>{
                    if(err){
                        console.log(err)
                    }
                })
            }
        })
    })

//删除文件
program.command('delete_file [name]')
    .action((name)=>{
        let pathname=path.join('./',name)
        if(fs.existsSync(pathname)){
            // 封装方法
            fileTree(pathname)
        }else{
            console.log('此文件不存在')
        }
    })

function fileTree(pathname){
        if(fs.statSync(pathname).isFile()){
            fs.unlinkSync(pathname)
        }else{
            const files=fs.readdirSync(pathname)
            files.forEach(item=>{
                fileTree(path.join(pathname,item))
            })
            fs.rmdirSync(pathname)
        }
}

let formItem=[{
    type:"checkbox",
    message:'请选择要合并的文件',
    name:'mergefiles',
    choices:fs.readdirSync('./')
},{
    type:"input",
    message:'请输入合并后的文件名',
    name:"newFileName"
},{
    type:"list",
    message:"请选择文件格式",
    choices:['.html','.css','.scss','.js','.ts','.json'],
    name:"newFileType"
}]
// 合并
program.command('merge_files')
    .action(()=>{
        inquirer.prompt(formItem).then(res=>{
            console.log(res)
            const {mergefiles,newFileName,newFileType}=res
            let content=''
            mergefiles.forEach(item=>{
                content+=fs.readFileSync(path.join('./',item),'utf-8')
                
            })
            fs.writeFileSync(newFileName+newFileType,content)
        })
    })

program.parse(process.rgv)